*****************************************************************************************
* This dofile aggregate the weekly USDM drought indicator data by year, season, and crop
*****************************************************************************************

clear all
cd "$root"

foreach crop in c_ s_ {  
	clear

	use data/raw/`crop'dates.dta

	merge 1:m st_fips using "data\raw\USDM\drought_weekly.dta"
	keep if _merge == 3
	drop _merge
	rename none d5

	generate start = date( validstart , "YMD")
	format %td start
	generate end = date( validend , "YMD")
	format %td end

	forvalues yr = 2000(1)2024 {

		* Define season starting/end points 
		gen `crop'dpa_begin`yr' = date(`crop'pa_begin_m + "/" + `crop'pa_begin_d + "/`yr'", "MDY")
		local pyr = `yr' - 1
		format %td `crop'dpa_begin`yr'

		gen `crop'dpa_end`yr' = date(`crop'pa_end_m + "/" + `crop'pa_end_d + "/`yr'", "MDY")
		format %td `crop'dpa_end`yr'

		gen `crop'dha_end1`yr' = date(`crop'ha_end_m + "/"+`crop'ha_end_d + "/`pyr'", "MDY")
		format %td `crop'dha_end1`yr'

		gen `crop'dha_end2`yr' = date(`crop'ha_end_m + "/" + `crop'ha_end_d + "/`yr'", "MDY")
		format %td `crop'dha_end2`yr'

		* Days in pre-season for each year
		gen temp1 = max(start, `crop'dha_end1`yr' + 1)
		format %td temp1

		gen temp2 = min(end, `crop'dpa_begin`yr')
		format %td temp2

		gen `crop'pre_`yr' = 0
		replace `crop'pre_`yr' = temp2 - temp1 + 1
		replace `crop'pre_`yr' = 0 if end <= `crop'dha_end1`yr' | start > `crop'dpa_begin`yr'
		drop temp* 

		* Days in planting season for each year
		gen temp1 = max(start, `crop'dpa_begin`yr')
		format %td temp1

		gen temp2 = min(end, `crop'dpa_end`yr')
		format %td temp2

		gen `crop'planting_`yr' = 0
		replace `crop'planting_`yr' = temp2 - temp1 + 1
		replace `crop'planting_`yr' = 0 if end <= `crop'dpa_begin`yr' | start>`crop'dpa_end`yr'
		drop temp* 

		* Days in growing season for each year
		gen temp1 = max(start, `crop'dpa_end`yr' + 1)
		format %td temp1

		gen temp2 = min(end, `crop'dha_end2`yr')
		format %td temp2

		gen `crop'growing_`yr' = 0
		replace `crop'growing_`yr' = temp2 - temp1 + 1
		replace `crop'growing_`yr' = 0 if end <= `crop'dpa_end`yr' | start > `crop'dha_end2`yr'
		drop temp* 

		forvalues i = 0(1)5 {
			* d`i' are percents 1~100, `crop'pre_`yr' is the number of days in that week to be in a certain season
			gen `crop'd`i'_b`yr' = d`i'*`crop'pre_`yr'/700  
			gen `crop'd`i'_p`yr' = d`i'*`crop'planting_`yr'/700
			gen `crop'd`i'_g`yr' = d`i'*`crop'growing_`yr'/700
		}
	}

	collapse  (rawsum) `crop'd*,by(fips)
	reshape long `crop'd0_b `crop'd1_b `crop'd2_b `crop'd3_b `crop'd4_b `crop'd5_b ///
				 `crop'd0_p `crop'd1_p `crop'd2_p `crop'd3_p `crop'd4_p `crop'd5_p ///
				 `crop'd0_g `crop'd1_g `crop'd2_g `crop'd3_g `crop'd4_g `crop'd5_g, i(fips) j(year)
	keep fips year `crop'*b `crop'*p `crop'*g
	
	save data/temp/`crop'usdm.dta, replace
}




